<template>
  <div class="purchase-item">
    <div class="header">
      <div class="left">
        <h3 class="title">{{ data.title }}</h3>
        <div class="tags">
          <span class="tag product-tag">{{ data.product_category }}</span>
          <!-- 添加角色标签 -->
          <span :class="['tag', getRoleTagClass(data.publisher?.role)]">{{ getRoleText(data.publisher?.role) }}</span>
        </div>
      </div>
      <div class="right">
        <span>{{ data.remaining_quantity }}/{{ data.total_quantity }}</span>
      </div>
    </div>

    <div class="info-list">
      <div class="info-row">
        <div class="info-item">
          <span class="label">名称：</span>
          <span>{{ data.product_name }}</span>
        </div>
        <div class="info-item">
          <span class="label">收购价格：</span>
          <span class="price">￥{{ data.price_offer }}/斤</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-item">
          <span class="label">收购地区：</span>
          <span>{{ data.region }}</span>
        </div>
        <div class="info-item">
          <span class="label">发布时间：</span>
          <span id="ptime">{{ formatDate(data.published_at) }}</span>
        </div>
      </div>
      <div class="info-row">
        <div class="info-item">
          <span class="label">截止时间：</span>
          <span>{{ formatDate(data.deadline) }}</span>
        </div>
        <div class="info-item">
          <span class="label">发布者：</span>
          <span>{{ data.publisher?.user_name }}</span>
        </div>
      </div>
    </div>

    <div class="content">
      {{ truncatedContent }}
    </div>

    <div class="footer">
      <el-button 
        type="primary" 
        size="small"
        @click="handleDetail(data.article_id)"
      >
        了解详情
      </el-button>

      <!-- 在 user 路由下显示 -->
      <template v-if="currentRoute === 'user'">
        <el-button 
          type="warning" 
          size="small"
          @click="handleExtend(data.article_id)"
          :loading="loading"
        >
          延长日期
        </el-button>
        <el-button 
          type="danger" 
          size="small"
          @click="handleEarlyEnd(data.article_id)"
          :loading="loading"
          style="margin-left: 8px"
        >
          提前截止
        </el-button>
      </template>
    </div>

    <!-- 延长日期的对话框 -->
    <el-dialog
      v-model="showExtendDialog"
      title="延长截止日期"
      width="400px"
    >
      <el-date-picker
        v-model="newDeadline"
        type="datetime"
        placeholder="选择新的截止时间"
        format="YYYY-MM-DD HH:mm"
        value-format="YYYY-MM-DD HH:mm:ss"
        :disabled-date="disabledDate"
        style="width: 100%"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showExtendDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmExtend" :loading="loading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineEmits, computed, ref, inject } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const $axios = inject('$axios')
const route = useRoute()
const loading = ref(false)
const showExtendDialog = ref(false)
const newDeadline = ref('')

const props = defineProps({
  data: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['view-detail', 'update'])

// 获取当前路由名称
const currentRoute = computed(() => {
  return route.path.split('/').pop()
})

// 添加截断内容的计算属性
const truncatedContent = computed(() => {
  if (!props.data.content) return ''
  return props.data.content.length > 20 
    ? props.data.content.slice(0, 20) + '...' 
    : props.data.content
})

// 添加角色文本转换函数
const getRoleText = (role) => {
  const roleMap = {
    'gov': '政府',
    'dealer': '经销商',
    'farmer': '农民'
  }
  return roleMap[role] || '未知身份'
}

// 添加角色标签样式类函数
const getRoleTagClass = (role) => {
  const classMap = {
    'gov': 'role-tag-gov',
    'dealer': 'role-tag-dealer',
    'farmer': 'role-tag-farmer'
  }
  return classMap[role] || 'role-tag-default'
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

const handleDetail = (articleId) => {
  emit('view-detail', articleId)
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 处理延长日期
const handleExtend = () => {
  showExtendDialog.value = true
  newDeadline.value = ''
}

// 确认延长日期
const confirmExtend = async () => {
  if (!newDeadline.value) {
    ElMessage.warning('请选择新的截止日期')
    return
  }

  try {
    loading.value = true
    const response = await $axios.put('/article', {
      article_id: props.data.article_id,
      deadline: newDeadline.value
    })

    if (response.data.code === 200) {
      ElMessage.success('延长日期成功')
      showExtendDialog.value = false
      emit('update', response.data.data)
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('延长日期失败：', error)
    ElMessage.error(error.response?.data?.msg || '操作失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理提前截止
const handleEarlyEnd = (articleId) => {
  ElMessageBox.confirm(
    '确定要提前截止该公告吗？此操作不可撤销。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      loading.value = true
      const now = new Date()
      const chinaTime = new Date(now.getTime() + 8 * 60 * 60 * 1000).toISOString().slice(0, 19).replace('T', ' ')
      const response = await $axios.put('/article', {
        article_id: articleId,
        deadline: chinaTime
      })

      if (response.data.code === 200) {
        ElMessage.success('提前截止成功')
        emit('update', response.data.data)
      } else {
        ElMessage.error(response.data.msg || '操作失败')
      }
    } catch (error) {
      console.error('提前截止失败：', error)
      ElMessage.error(error.response?.data?.msg || '操作失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}
</script>

<style lang="less" scoped>
.purchase-item {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

  .header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;

    .left {
      .title {
        font-size: 18px;
        color: #303133;
        margin: 0 0 12px;
        font-weight: normal;
      }

      .tags {
        display: flex;
        gap: 8px;

        .tag {
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 12px;
        }

        .product-tag {
          background: #e8f5e9;
          color: #319A19;
        }

        // 添加不同角色的标签样式
        .role-tag-gov {
          background: #e6f7ff;
          color: #1890ff;
        }

        .role-tag-dealer {
          background: #fff7e6;
          color: #fa8c16;
        }

        .role-tag-farmer {
          background: #f6ffed;
          color: #52c41a;
        }

        .role-tag-default {
          background: #f5f5f5;
          color: #666;
        }
      }
    }

    .right {
      color: #303133;
      font-size: 14px;
    }
  }

  .info-list {
    .info-row {
      display: flex;
      margin-bottom: 16px;
      
      .info-item {
        flex: 1;
        display: flex;
        align-items: center;
        flex-wrap: nowrap;
        height: 30px;
        line-height: 30px;
        .label {
          flex-shrink: 0;
          color: #909399;
          // margin-right: 8px;
        }

        span {
          color: #303133;
        }

        .price {
          color: #f56c6c;
        }

        #ptime{
          width: 156px;
          height: 30px;
          line-height: 30px;
        }
      }
    }
  }

  .content {
    margin: 16px 0;
    padding: 16px 0;
    color: #606266;
    font-size: 14px;
    line-height: 1.6;
    border-top: 1px solid #ebeef5;
    border-bottom: 1px solid #ebeef5;
  }

  .footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
    gap: 8px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 20px;
}

@media screen and (max-width: 768px) {
  .purchase-item {
    padding: 16px;

    .info-list {
      .info-row {
        flex-direction: column;
        gap: 12px;

        .info-item {
          width: 100%;
        }
      }
    }
  }
}
</style>